﻿using CTP.CRM.Core.Common.Constants;
using CTP.CRM.Core.ExRedis;
using CTP.CRM.Repository.User.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CTP.CRM.Repository.User.Services
{
    /// <summary>
    /// 用户信息仓储
    /// </summary>
    public class UserRepository : BasicRepository<UserEntity>, IUserRepository, IScopedDependency
    {
        private static string cacheUserEntityKey = RedisKeyManage.GetUserListKey();

        private async Task<bool> AddRedisCacheWithHash(string hashKey, UserEntity entity)
        {
            var propertyInfos = entity.GetType().GetProperties();
            foreach (var item in propertyInfos)
            {
                await ExRedisHelper.Client.HSetAsync(hashKey, item.Name, item.GetValue(entity));
            }
            return true;
        }

        public async Task<bool> AddCacheUserAsync()
        {
            await ExRedisHelper.Client.DelAsync(cacheUserEntityKey);
            var result = await GetListAsync(x => x.IsDeleted == false);
            await ExRedisHelper.Client.SetAsync(cacheUserEntityKey, result, (int)TimeSpan.FromHours(24).TotalSeconds);
            return true;
        }

        public async Task<List<UserEntity>> GetCacheUserListAsync()
        {
            var result = await ExRedisHelper.Client.GetAsync<List<UserEntity>>(cacheUserEntityKey);
            if (result is null || !result.Any())
            {
                result = await GetListAsync(x => x.IsDeleted == false);
                await ExRedisHelper.Client.SetAsync(cacheUserEntityKey, result, (int)TimeSpan.FromHours(24).TotalSeconds);
            }
            return result;
        }

        public async Task<List<UserEntity>> GetCacheUserListAsync(Predicate<UserEntity> match)
        {
            var entitys = await GetCacheUserListAsync();
            var result = entitys.FindAll(match);
            return result;
        }

        public async Task<UserEntity> GetCacheUserEntityAsync(Predicate<UserEntity> match)
        {
            var entitys = await GetCacheUserListAsync();
            var result = entitys.Find(match);
            return result;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        public async Task<int> AddUserAsync(UserEntity userEntity)
        {
            int id = await InsertReturnIdentityAsync(userEntity);
            await AddCacheUserAsync();
            return id;
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        public async Task<bool> EditUserAsync(UserEntity userEntity)
        {
            string cacheSingleUserKey = RedisKeyManage.GetCurrentUserBasicInfoKey($"{userEntity.Id}");
            await ExRedisHelper.Client.DelAsync(cacheSingleUserKey);

            await AsUpdateable(userEntity).IgnoreColumns(x => new { x.IsDeleted, x.CreateTime, x.CreateUserId, x.PassWord }).ExecuteCommandHasChangeAsync();
            await AddCacheUserAsync();
            return true;
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        public async Task<bool> EditUserWithPwdAsync(UserEntity userEntity)
        {
            await AsUpdateable(userEntity).IgnoreColumns(x => new { x.IsDeleted, x.CreateTime, x.CreateUserId }).ExecuteCommandHasChangeAsync();
            await AddCacheUserAsync();
            return true;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        public async Task<bool> RemoveUserAsync(UserEntity userEntity)
        {
            bool isSuccess = await AsUpdateable(userEntity).UpdateColumns(x => new { x.IsDeleted, x.UpdateTime, x.UpdateUserId }).ExecuteCommandHasChangeAsync();
            if (isSuccess)
            {
                string cacheSingleUserKey = RedisKeyManage.GetCurrentUserBasicInfoKey($"{userEntity.Id}");
                await ExRedisHelper.Client.DelAsync(cacheSingleUserKey);
                await AddCacheUserAsync();
            }
            return true;
        }

        /// <summary>
        /// 根据id获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<UserEntity> GetUserById(int id)
        {
            return await GetFirstAsync(x => x.Id == id);
        }

        /// <summary>
        /// 判断集合数据是否全部存在
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> IsAllAsync(params int[] ids)
        {
            return (await base.AsQueryable().CountAsync(it => it.IsDeleted != true && ids.Contains(it.Id))) == ids.Distinct().Count();
        }

        public async Task<bool> EditUserPassWordAsync(UserEntity userEntity)
        {
            await AsUpdateable(userEntity).UpdateColumns(x => new { x.PassWord, x.UpdateTime, x.UpdateUserId }).ExecuteCommandHasChangeAsync();
            await AddCacheUserAsync();
            return true;
        }

      
    }
}
